package com.baorant.resouceserverapplication.utils;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class HttpClientWithBasicAuth {

    public HttpClientWithBasicAuth() {
    }

    /**
     * 手动构造Basic Auth认证头信息
     *
     * @return
     */
    private String getHeader(String UserName, String Password) {
        String auth = UserName + ":" + Password;
        byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII")));// 加密
        String authHeader = "Basic " + new String(encodedAuth);
        return authHeader;
    }

    /**
     * 向指定的认证服务发送请求，以获取access token
     * @param url 认证服务的URL
     * @param UserName 应用程序的Client_Id
     * @param Password 应用程序的Client_secret
     * @param params 包含grant_type和scope的参数列表
     * @return 响应内容
     */
    public String send(String url, String UserName, String Password, Map<String, String> params) {
        HttpPost post = new HttpPost(url);
        CloseableHttpClient client = HttpClients.createDefault();
        // 组织请求参数，在获取token时参数为grant_type和scope
        List<NameValuePair> paramList = new ArrayList<NameValuePair>();

        if (params != null && params.size() > 0) {
            Set<String> keySet = params.keySet();
            for (String key : keySet) {
                paramList.add(new BasicNameValuePair(key, params.get(key)));
            }
        }
        try {
            post.setEntity(new UrlEncodedFormEntity(paramList, "utf-8"));
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }

        post.addHeader("Authorization", getHeader(UserName, Password));
        // post.setEntity(myEntity);// 设置请求体
        String responseContent = null; // 响应内容
        CloseableHttpResponse response = null;
        try {
            response = client.execute(post);
            // System.out.println(JSON.toJSONString(response));
            int status_code = response.getStatusLine().getStatusCode();
            // System.out.println("status_code:" + status_code);
            // if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();

            responseContent = EntityUtils.toString(entity, "UTF-8");
            // }
            // System.out.println("responseContent:" + responseContent);
        } catch (IOException e) {
            e.printStackTrace();

        } finally {
            try {
                if (response != null)
                    response.close();

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (client != null)
                        client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return responseContent;
    }
}


